package org.jeecg.modules.cqb.util;

import cn.hutool.core.net.multipart.UploadFile;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;

/**
 *
 * @author long
 *
 */
public class CreateWordUtil implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

    private static  final String TEMPLATE_URL="/com/yixiekeji/web/templates";
    //private static  final String CREATE_WORD_URL = "C:\\Custmore\\junzhang\\Downloads\\";//本地环境

    private static  final String CREATE_WORD_URL = "~/users/contract/downloads";//服务器环境

    private Configuration configuration;
    private String fileWordName;
    private String fileWordTemplate;

    public CreateWordUtil(String fileWordName, String fileWordTemplete) {
       configuration= new Configuration();
        //空值处理
       configuration.setClassicCompatible(true);
       configuration.setDefaultEncoding("utf-8");
       this.fileWordName=fileWordName;
       this.fileWordTemplate=fileWordTemplete;
   }
  /**
   *
   * @author jianglong
   * @param dataMap Map
   */
   public String createDoc(Map dataMap) {
       configuration.setClassForTemplateLoading(this.getClass(), TEMPLATE_URL);
       Template t=null;
       String path = CREATE_WORD_URL + fileWordName;
       try {
           //test.ftl为要装载的模板
           t = configuration.getTemplate(fileWordTemplate);
       } catch (IOException e) {
           e.printStackTrace();
       }
       //输出文档路径及名称
       File outFile = new File(path);
       //创建目录
       if(!outFile.getParentFile().exists()){
    	   outFile.getParentFile().mkdirs();
   	   }
       Writer out = null;
       try {
           out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
            //解决出现乱码
           //out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8"));
           if (t != null){
               t.process(dataMap, out);
           }
       } catch (Exception e) {
           e.printStackTrace();
       }finally{
           try {
               if (out != null){
                   out.close();
               }
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }
       return path;
   }

}
